from fastapi import APIRouter, Body, Request, Depends
from server.db.models.memory_model import MemoryNode, DeleteMemoryNodeRecord, Memory
from server.db.models.message_model import MarsXTrainModeSession
from server.db.session import get_db
from sqlalchemy.orm import Session
import json
from http import HTTPStatus
from server.utils import BaseResponse, decode_verify_token
from loguru import logger
from configs.logging_config import configure_logging
from server.bailian.memory_client import client as memory_client
from sqlalchemy import and_
from configs.kb_config import GO_SERVICE_SECRET_KEY
from configs.other_config import ALGORITHM
configure_logging()

router = APIRouter()

@router.post("/bailian/v1/delete_memory_node")
async def delete_memory_node_v1(content: str = Body(..., embed=True, description="记忆片段内容"), 
                                uid: str = Body(..., embed=True, description="用户ID"), 
                                delete_content: bool = Body(True, description="是否删除记忆片段内容"),
                                request: Request = None,
                                db: Session = Depends(get_db)):
    # 解码token
    try:
        token = decode_verify_token(request, GO_SERVICE_SECRET_KEY, ALGORITHM)
    except Exception as e:
        return BaseResponse(code=401, msg="Token is invalid", data={"error": str(e.detail.get('msg'))})
    request_type = 3
    mars_train_mode_session_object = db.query(MarsXTrainModeSession).filter(and_(MarsXTrainModeSession.user_id == uid, MarsXTrainModeSession.user_input == content, MarsXTrainModeSession.pet_input == "", MarsXTrainModeSession.train_type == "heart")).first()
    memory_object = db.query(Memory).filter(Memory.user_id == uid, Memory.memory_id != "").first()
    if mars_train_mode_session_object:
        memory_node_id = mars_train_mode_session_object.memory_node_id
        if memory_object is not None:
            memory_id = memory_object.memory_id
        else:
            logger.error(f"记忆体不存在 用户ID: {uid} | 记忆片段内容: {content}")
            return BaseResponse(
                code=HTTPStatus.INTERNAL_SERVER_ERROR,
                msg="要删除的记忆片段所属的记忆体不存在",
                data={
                    "content": content,
                    "memory_node_id": memory_node_id,
                    "uid": uid
                }
            )
        memory_node_object = db.query(MemoryNode).filter(MemoryNode.memory_node_id == memory_node_id).first()
        if memory_node_object is None:
            logger.error(f"记忆片段不存在 用户ID: {uid} | 记忆片段内容: {content}")
            return BaseResponse(
                code=HTTPStatus.INTERNAL_SERVER_ERROR,
                msg="记忆片段不存在",
                data={
                    "content": content,
                    "memory_node_id": memory_node_id,
                    "uid": uid
                }
            )
        try:
            delete_memory_node_response = memory_client.delete_memory_node(memory_id=memory_id, memory_node_id=memory_node_id)
        except Exception as e:
            if "MemoryNodeNotFound" in str(e):
                logger.error(f"记忆片段不存在 用户ID: {uid} | 记忆片段内容: {content} | 错误信息: {e}")
                return BaseResponse(
                    code=HTTPStatus.INTERNAL_SERVER_ERROR,
                    msg="记忆片段不存在",
                    data={
                        "content": content,
                        "memory_node_id": memory_node_id,
                        "uid": uid
                    }
                )
            logger.error(f"删除记忆片段失败 用户ID: {uid} | 记忆片段内容: {content} | 错误信息: {e}")
            return BaseResponse(
                code=HTTPStatus.INTERNAL_SERVER_ERROR,
                msg="删除记忆片段失败",
                data={
                    "content": content,
                    "memory_node_id": memory_node_id,
                    "uid": uid
                }
            )
        delete_memory_node_request_id = delete_memory_node_response["requestId"]
        new_delete_memory_node_record_object = DeleteMemoryNodeRecord(
            user_id=uid,
            workspace_id=memory_node_object.workspace_id,
            memory_id=memory_node_object.memory_id,
            memory_node_id=memory_node_id,
            request_id=delete_memory_node_request_id,
            request_type=request_type,
            deleted_content_type="heart"
        )
        try:
            db.add(new_delete_memory_node_record_object)
            db.delete(memory_node_object)
            db.commit()
        except Exception as e:
            db.rollback()
            logger.error(f"删除记忆片段时数据库操作失败1 用户ID: {uid} | 记忆片段内容: {content} | 错误信息: {e}")
            return BaseResponse(
                code=HTTPStatus.INTERNAL_SERVER_ERROR,
                msg="删除记忆片段时数据库操作失败1",
                data={
                    "content": content,
                    "memory_node_id": memory_node_id,
                    "uid": uid
                }
            )
        return BaseResponse(code=HTTPStatus.OK, msg="success", data={"memory_node_id": memory_node_id})
    else:
        logger.error(f"记忆片段不存在 用户ID: {uid} | 记忆片段内容: {content}")
        return BaseResponse(
            code=HTTPStatus.INTERNAL_SERVER_ERROR,
            msg="记忆片段不存在",
            data={
                "content": content,
                "uid": uid,
                "memory_node_id": ""
            }
        )